package com.fsp.jianchi.jgjplayer;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.os.StatFs;
import android.os.storage.StorageManager;
import android.support.v7.app.NotificationCompat;
import android.text.TextUtils;
import android.widget.RemoteViews;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;

public class PlayerService extends Service {
    private NotificationManager notificationManager;

    NotificationEventListener notificationEventListener;

    private MediaPlayer mp;
    public List<String> songsList;//当前播放列表
    public int mp3Id;//当前播放音乐在列表中的位置
    public int progress;//歌曲的进度

    public String mp3Path;
    String mp3PathName = "净空法师金刚经讲记";
    String exDirPaht;

    IBinder binder;
    IMusic music;
    boolean isOk=false;

    Notification notification=null;

    public PlayerService() {
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        //检测有没有初始化
        if(songsList==null) {
            //在这里获取MP3列表
            songsList = getMp3Files();
            if (songsList.size() > 0) {
                //实例化SharedPreferences对象（第一步）
                SharedPreferences mSharedPreferences = getApplicationContext().getSharedPreferences("playStatus", Context.MODE_PRIVATE);
                mp3Id = mSharedPreferences.getInt("mp3Id", 0);
                progress = mSharedPreferences.getInt("pos", 0);

                notificationManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);

                binder = new MusicListener();
                music = (IMusic)binder;

                initNotificationBar(songsList.get(mp3Id));

                mp = new MediaPlayer();
                mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        music.nextSong();
                    }
                });

                mp.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                    public boolean onError(MediaPlayer mp, int what, int extra) {
                        // TODO Auto-generated method stub
                        mp.release();
                        return false;
                    }
                });

                mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        mp.seekTo(progress);
                        mp.start();
                    }
                });

                isOk=true;


            }
        }
        return binder;
    }

    void saveProcess(){
        SharedPreferences mSharedPreferences = getApplicationContext().getSharedPreferences("playStatus", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putInt("mp3Id", mp3Id);
        if(mp!=null)
            editor.putInt("pos", mp.getCurrentPosition());
        else
            editor.putInt("pos", progress);
        editor.commit();
    }

    List<String> getMp3Files(){
        List<String> ss = getExtSDCardPath();
        TreeSet<String> list = new TreeSet<String>();
        if(ss.size()>0)
        {
            exDirPaht = ss.get(0);
            exDirPaht += exDirPaht.endsWith("/")?"":"/";
            mp3Path = exDirPaht+mp3PathName;
            File mp3Dir = new File(mp3Path);
            if(mp3Dir.exists()){
                String[] fs = mp3Dir.list();
                for(String s : fs){
                    if(s.toLowerCase().endsWith(".mp3"))
                        list.add(s);
                }
            }
        }

        List<String> mp3ss = new ArrayList<>(list.size());
        for(String s : list)
            mp3ss.add(s);

        return mp3ss;
    }

    public List<String> getExtSDCardPath()
    {
        List<String> pathsList = new ArrayList<String>();
        StorageManager storageManager = (StorageManager) getSystemService(STORAGE_SERVICE);
        try {
            Method method = StorageManager.class.getDeclaredMethod("getVolumePaths");
            method.setAccessible(true);
            Object result = method.invoke(storageManager);
            if (result != null && result instanceof String[]) {
                String[] pathes = (String[]) result;
                StatFs statFs;
                for (String path : pathes) {
                    if (!TextUtils.isEmpty(path) && new File(path).exists() && path.indexOf("sdcard")>0) {
                        pathsList.add(path);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            File externalFolder = Environment.getExternalStorageDirectory();
            if (externalFolder != null) {
                pathsList.add(externalFolder.getAbsolutePath());
            }
        }
        return pathsList;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        saveProcess();
        notificationManager.cancel(Const.NOTI_CTRL_ID);//关闭通知
        music.stop();
        super.onDestroy();
    }

    private void initNotificationBar(String msg) {
        if(notification==null) {
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(PlayerService.this);
            RemoteViews view = new RemoteViews(getPackageName(), R.layout.ntf_item);
            view.setTextViewText(R.id.textView, msg);

            Intent intent = new Intent(PlayerService.this, MainActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(PlayerService.this, 0, intent, 0);

/*

            Intent intentPlay = new Intent("play");//新建意图，并设置action标记为"play"，用于接收广播时过滤意图信息
            PendingIntent pIntentPlay = PendingIntent.getBroadcast(this, 0,
                    intentPlay, 0);
            contentView.setOnClickPendingIntent(R.id.bt_notic_play, pIntentPlay);//为play控件注册事件

            Intent intentPause = new Intent("pause");
            PendingIntent pIntentPause = PendingIntent.getBroadcast(this, 0,
                    intentPause, 0);
            contentView.setOnClickPendingIntent(R.id.bt_notic_pause, pIntentPause);

            Intent intentNext = new Intent("next");
            PendingIntent pIntentNext = PendingIntent.getBroadcast(this, 0, intentNext, 0);
            contentView.setOnClickPendingIntent(R.id.bt_notic_next, pIntentNext);

            Intent intentLast = new Intent("last");
            PendingIntent pIntentLast = PendingIntent.getBroadcast(this, 0, intentLast, 0);
            contentView.setOnClickPendingIntent(R.id.bt_notic_last, pIntentLast);

            Intent intentCancel = new Intent("cancel");
            PendingIntent pIntentCancel = PendingIntent.getBroadcast(this, 0, intentCancel, 0);
            contentView.setOnClickPendingIntent(R.id.bt_notic_cancel, pIntentCancel);
            notification.flags = notification.FLAG_NO_CLEAR;//设置通知点击或滑动时不被清除
            application.notManager.notify(Const.NOTI_CTRL_ID, notification);//开启通知
            */

            mBuilder.setSmallIcon(R.drawable.ic_launcher)
                    .setTicker("净空法师金刚经讲记")
                    .setOngoing(true)
                    .setContentIntent(pendingIntent)
                    .setContent(view);
            notification = mBuilder.build();

            notification.flags = notification.FLAG_NO_CLEAR;//设置通知点击或滑动时不被清除
        }
        else {
            notification.contentView.setTextViewText(R.id.textView, msg);
        }

        notificationManager.notify(Const.NOTI_CTRL_ID, notification);//开启通知
    }

    public class MusicListener extends Binder implements IMusic {

        @Override
        public void moveon(int playMp3Id, int pos) {
            mp3Id = playMp3Id;//在全局变量中标记当前播放位置
            progress = pos;

            if (mp3Id >= 0) {
                mp3Id = mp3Id % songsList.size();
            } else {
                mp3Id = songsList.size() + mp3Id;
            }

            String currentSong = mp3Path +"/"+ songsList.get(mp3Id);//获取当前播放音乐

            File mp3File = new File(currentSong);
            if (mp3File.exists()) {
                mp.reset();

                try {
                    mp.setDataSource(mp3File.getAbsolutePath());
                    // Prepare to async playing
                    mp.prepareAsync();
                    //mp.prepare();
                    //mp.start();
                    initNotificationBar(songsList.get(mp3Id));

                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void play() {
            moveon(mp3Id, progress);
        }


        @Override
        public void pause() {
            progress = mp.getCurrentPosition();
            mp.pause();
        }

        @Override
        public void nextSong() {
            moveon(++mp3Id, 0);

            if (notificationEventListener != null)
                notificationEventListener.handleEvent();
        }

        @Override
        public void stop() {
            progress = mp.getCurrentPosition();
            mp.stop();
            mp.release();
            mp = null;
        }


        @Override
        public int getMp3Id() {
            return mp3Id;
        }

        @Override
        public List<String> getMp3s() {
            return songsList;
        }

        @Override
        public boolean isOk() {
            return isOk;
        }

        @Override
        public void setNotificationEventListener(NotificationEventListener listener) {
            notificationEventListener=listener;
        }
    }
}
